import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import * as _ from 'lodash';
import * as moment from 'moment';
import { DataService } from '../../../../services/data.service';
import { FormsModule, FormGroup, FormControl } from '@angular/forms';
import { WclService } from './wcl.service';
import { LayoutComponent } from "../../../global/layout/layout.component";
import { environment } from '../../../../../environments/environment';
import { AppPaginationComponent, PaginationModel } from "../../../../widgets/pagination/pagination.component";

@Component({
  selector: 'app-wcl',
  templateUrl: './wcl.component.html',
  styleUrls: ['./wcl.component.scss'],
  providers: [WclService]
})
export class WclComponent implements OnInit {
  // lodash
  public _: any = _;
  // 菜单数据
  public menuData: any;
  //  托管人数据
  // public bankDictionaryList = [];
  // 菜单按钮集合
  public menuResourceSet: any;
  // 一对一单个产品信息
  public otoProductBody: any = {};
  //查询分页列表post数据
  public getOneononePost = {
    pageIndex: 1,
    pageSize: 10,
    sFullName: '',
    sFundCode: '',
    sFundStatus: 1,
    sStatusRunning: '',
    sTrustee: '',
    sPrincipal: ''
  };
  // 备案机构、受托人、托管人
  public distionary: any = {
    RECORDORG_TYPE: [],  // 备案机构
    LINK_PRINCIPAL_NO: [],   //受托人
    TRUSTEE: []   //  托管人
  }
  //一对一分页配置
  public oneononeListPageInfo: PaginationModel = {
    currentPageNum: 1,
    pageSize: 10,
    totalPages: 1,
    total: 0,
    pagesShow: 5,
    startRow: 0,
    endRow: 0,
    pageList: [5, 10, 25, 50, 100]
  };
  //一对一分页列表list
  public oneononeList = [];
  // 列表是否全选
  public isCheckedAll = false;

  constructor(
    public router: Router,
    public layoutComponent: LayoutComponent,
    public wclService: WclService,
    public dataservice: DataService
  ) {
    this.list();
  }

  ngOnInit() {
    let that = this;
    sessionStorage.setItem('oto_isStop', 'isnoStop');
    // 权限处理
    this.dataservice.initTree.subscribe((data) => {
      let SessionMenuData = sessionStorage.getItem('menu');
      this.menuData = JSON.parse(SessionMenuData)
      this.menuResourceSet = [];
      _.forEach(this.menuData, (item, index) => {
        if (item.sName == '一对一专户') {
          _.forEach(item.children, (it, idx) => {
            if (it.sName == '未成立') {
              that.menuResourceSet = it.resourceSet
              sessionStorage.setItem('btn-oto', that.menuResourceSet);
            }
          })
        }
      })
    })
    let SessionMenuData = sessionStorage.getItem('menu');
    this.menuData = JSON.parse(SessionMenuData)
    this.menuResourceSet = [];
    _.forEach(this.menuData, (item, index) => {
      if (item.sName == '一对一专户') {
        _.forEach(item.children, (it, idx) => {
          if (it.sName == '未成立') {
            that.menuResourceSet = it.resourceSet
            sessionStorage.setItem('btn-oto', that.menuResourceSet);
          }
        })
      }
    })
    this.getDictionary();
    // 获取托管人数据
    // this.bankDictionaryList = JSON.parse(localStorage.getItem("bankDictionaryList"));
  }

  // 查询分页列表
  list(pageNum?, pageSize?) {
    let that = this;
    this.isCheckedAll = false;
    this.getOneononePost.sFullName = _.trim(this.getOneononePost.sFullName);
    this.getOneononePost.sFundCode = _.trim(this.getOneononePost.sFundCode);
    this.getOneononePost.sPrincipal = _.trim(this.getOneononePost.sPrincipal);
    this.getOneononePost.sTrustee = _.trim(this.getOneononePost.sTrustee);
    this.getOneononePost.pageIndex = pageNum ? pageNum : this.oneononeListPageInfo.currentPageNum;
    this.getOneononePost.pageSize = pageSize ? pageSize : this.oneononeListPageInfo.pageSize;
    this.wclService.list(this.getOneononePost).subscribe(data => {
      if (data) {
        that.oneononeList = data.list;
        that.oneononeListPageInfo.currentPageNum = data.pageNum;
        that.oneononeListPageInfo.totalPages = data.pages;
        that.oneononeListPageInfo.total = data.total;
        that.oneononeListPageInfo.startRow = data.startRow;
        that.oneononeListPageInfo.endRow = data.endRow;
      }
    });
  }
  // 个数分页
  oneononepageSizeChange(pageSize: number) {
    if (pageSize !== this.oneononeListPageInfo.pageSize) {
      this.oneononeListPageInfo.pageSize = pageSize;
      this.list();
    }
  }
  // 页码分页
  oneononePageNavigation(currentPageNum: number) {
    this.oneononeListPageInfo.currentPageNum = currentPageNum;
    this.list(this.oneononeListPageInfo.currentPageNum, this.oneononeListPageInfo.pageSize);
  }
  // 列表全选
  checkedAll() {
    if (this.isCheckedAll) { // 更新为全选
      _.forEach(this.oneononeList, item => {
        item.isChecked = true;
      });
    } else { // 更新为不全选
      _.forEach(this.oneononeList, item => {
        item.isChecked = false;
      });
    }
  }
  // 列表是否全选
  ctrlCheckAll() {
    let that = this;
    let checkList = [];
    _.forEach(this.oneononeList, item => {
      if (item.isChecked == true) {
        checkList.push(item);
      }
    })
    if (checkList.length == this.oneononeList.length) {
      this.isCheckedAll = true;
    } else {
      this.isCheckedAll = false;
    }
  }
  // 删除产品
  delProduct() {
    let that = this;
    let checkedItem = [];
    let checkedFundName = [];
    _.forEach(that.oneononeList, item => {
      if (item.isChecked == true) {
        checkedItem.push(item.nFundNo);
        checkedFundName.push(item.sFundName);
      }
    })
    let checkedTips = checkedFundName.join("、");
    if (checkedItem.length > 0) {
      window['swal']({
        type: "warning",
        showCancelButton: true,
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        closeOnConfirm: false,
        showLoaderOnConfirm: true,
        title: "提示",
        text: "<div style='max-height: 200px;overflow-y: auto;'>" + "请确认是否删除产品：" + checkedTips + "</div>",
        html: true
      },
        function (isConfirm) {
          if (isConfirm) {
            let putBody: any = {
              "nFundNoMap": checkedItem
            }
            that.wclService.del(putBody).subscribe(data => {
              if (data) {
                window['swal']("删除成功！", "", "success")
                that.list();
              }
            })
          }
        })
    }
    else {
      window['swal']("提示", "请选择一个或多个产品进行删除", "warning")
    }
  }
  // 导出
  exportExcel() {
    let that = this;
    let checkedItem = [];
    _.forEach(that.oneononeList, item => {
      if (item.isChecked == true) {
        checkedItem.push(item.nFundNo);
      }
    })
    let converItem: any = checkedItem.join(',');
    let getBody = {
      "nFundNoList": converItem,
      "sFundStatus": this.getOneononePost.sFundStatus,
      "sFullName": this.getOneononePost.sFullName,
      "sFundCode": this.getOneononePost.sFundCode,
      "sStatusRunning": this.getOneononePost.sStatusRunning,
      "sTrustee": this.getOneononePost.sTrustee,
      "sPrincipal": this.getOneononePost.sPrincipal
    }
    const iframe = window['$']("<iframe id='downloadiframe'>");
    iframe.attr('style', 'display:none');
    //  转码，兼容ie
    getBody.sFullName = encodeURI(getBody.sFullName)
    getBody.sTrustee = encodeURI(getBody.sTrustee)
    getBody.sFundCode = encodeURI(getBody.sFundCode)
    getBody.sPrincipal = encodeURI(getBody.sPrincipal)
    iframe.attr('src', environment.server + '/pms/v1/oneOnOneFundInfo/export/oneOnOneInfo?token=' + sessionStorage.getItem('token') + '&nFundNoList=' + getBody.nFundNoList + '&sFundStatus=' + getBody.sFundStatus + '&sFullName=' + getBody.sFullName + '&sFundCode=' + getBody.sFundCode + '&sStatusRunning=' + getBody.sStatusRunning+ '&sTrustee=' + getBody.sTrustee+ '&sPrincipal=' + getBody.sPrincipal);
    window['$']('body').append(iframe);
    setTimeout("$('#downloadiframe').remove()", 60000);
  }
  // 产品新增
  create() {
    sessionStorage.setItem('currentTitle', "创设·一对一");
    this.layoutComponent.nav(null, null, "创设·一对一");
    this.router.navigate(['pages/onetoone/new/detail/add']);
  }
  // 切换产品状态
  changeProductStatus(item, type) {
    let that = this;
    if (type == 'stop') {
      window["swal"]({
        title: "提示",
        text: "是否将产品状态更改为暂停",
        type: "warning",
        confirmButtonText: "确认",
        confirmButtonColor: "#DD6B55",
        cancelButtonText: "取消",
        showCancelButton: true,
        closeOnConfirm: false,
        closeOnCancel: true,
        showLoaderOnConfirm: true
      },
        function (isConfirm) {
          if (isConfirm) {
            that.wclService.changeProductStatus(item.nFundNo, type).subscribe(data => {
              if (data) {
                window["swal"]("成功", "产品停止运行!", "success");
                that.list();
              }
            })
          }
        })
    }
    if (type == 'run') {
      window["swal"]({
        title: "提示",
        text: "是否将产品状态更改为运行",
        type: "warning",
        confirmButtonText: "确认",
        confirmButtonColor: "#DD6B55",
        cancelButtonText: "取消",
        showCancelButton: true,
        closeOnConfirm: false,
        closeOnCancel: true,
        showLoaderOnConfirm: true
      },
        function (isConfirm) {
          if (isConfirm) {
            that.wclService.changeProductStatus(item.nFundNo, type).subscribe(data => {
              if (data) {
                window["swal"]("成功", "产品开始运行!", "success");
                that.list();
              }
            })
          }
        })
    }
  }
  // 产品修改
  edit(type, item?) {
    let that = this;
    sessionStorage.setItem('parentIndex', 'wcl');
    let checkProduct = [];
    switch (type) {
      case 'dbclick':
        sessionStorage.setItem('currentTitle', "详情·未成立·一对一");
        this.layoutComponent.nav(null, null, "详情·未成立·一对一");
        this.router.navigate(['pages/onetoone/wcl/detail/edit/' + item.nFundNo]);
        break;
      case 'one':
        _.forEach(that.oneononeList, it => {
          if (it.isChecked == true) {
            checkProduct.push(it);
          }
        })
        if (checkProduct.length == 1) {
          sessionStorage.setItem('currentTitle', "详情·未成立·一对一");
          this.layoutComponent.nav(null, null, "详情·未成立·一对一");
          this.router.navigate(['pages/onetoone/wcl/detail/edit/' + checkProduct[0].nFundNo]);
        } else {
          window['swal']("提示", "请选择一个产品进行查看", "warning");
        }
        break;
    }
  }
  // 点击表格头排序
  orderData(colName) {
    let listDataAsc = _.orderBy(this.oneononeList, [colName], ["asc"]);
    if (JSON.stringify(this.oneononeList) == JSON.stringify(listDataAsc)) {
      listDataAsc = _.orderBy(this.oneononeList, [colName], ["desc"]);
    }
    this.oneononeList = listDataAsc;
  }

  // 获取备案机构、受托人、托管人下拉框值
  getDictionary() {
    let that = this;
    this.wclService.getDictionary().subscribe(data => {
      if (data) {
        that.distionary.RECORDORG_TYPE = data.RECORDORG_TYPE;
        that.distionary.LINK_PRINCIPAL_NO = data.LINK_PRINCIPAL_NO;
        that.distionary.TRUSTEE = data.TRUSTEE;
      }
    })
  }
  ngAfterViewInit() {
    let that = this;
    // 多选下拉框
    window['$'](".select2").select2();
    window['$']('#sTrusteeSelected').select2({ width: '182px', tags: true });
    window['$']('#sTrusteeSelected').on("select2:select", function (e) {
      that.getOneononePost.sTrustee = window['$']('#sTrusteeSelected').select2("val");
    })
  }
}

